package com.eds.gateway.filter;

import com.eds.jwt.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.web.server.context.ServerSecurityContextRepository;
import org.springframework.security.web.server.context.WebSessionServerSecurityContextRepository;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.util.Collections;

@Component
public class JwtAuthenticationFilter implements WebFilter {

    private final ServerSecurityContextRepository securityContextRepository =
            new WebSessionServerSecurityContextRepository();
    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        String path = exchange.getRequest().getPath().value();
        System.out.println("Current path: " + path);

        String token = extractToken(exchange);
        System.out.println("Extracted token: " + token);

        if (token != null) {
            try {
                // 打印token的验证结果
                System.out.println("Token validation result: " + jwtUtils.validateToken(token));

                // 打印解析出的用户信息
                String username = jwtUtils.getUsernameFromToken(token);
                String role = jwtUtils.getRoleFromToken(token);
                System.out.println("Username from token: " + username);
                System.out.println("Role from token: " + role);

                if (jwtUtils.validateToken(token)) {
                    UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
                            username, null, Collections.singletonList(
                            new SimpleGrantedAuthority(role)
                    ));
                    System.out.println("Created authentication token with authorities: " + auth.getAuthorities());

                    SecurityContextImpl securityContext = new SecurityContextImpl(auth);
                    return securityContextRepository.save(exchange, securityContext)
                            .then(chain.filter(exchange));
                }
            } catch (Exception e) {
                System.out.println("Error processing token: " + e.getMessage());
                e.printStackTrace();
            }
        }

        System.out.println("No valid token found, continuing filter chain");
        return chain.filter(exchange);
    }

    private boolean isPermitAllPath(String path) {
        return path.startsWith("/userService/userController/login") ||
                path.startsWith("/userService/userController/register") ||
                path.startsWith("/captchaService") ||
                path.equals("/") ||
                path.startsWith("/static") ||
                path.equals("/login") ||
                path.equals("/register") ||
                path.equals("/home") ||
                path.equals("/forgot-password") ||
                path.endsWith(".ico") ||
                path.endsWith(".png") ||
                path.endsWith(".js") ||
                path.endsWith(".css") ||
                path.startsWith("/assets/");
    }

    private String extractToken(ServerWebExchange exchange) {
        String bearerToken = exchange.getRequest().getHeaders().getFirst("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}